<script setup>
import axios from "axios";
import { ref, onMounted, onUnmounted } from "vue";
const api = "https://vue3-course-api.hexschool.io/api/panya/products/all";
let products = ref([]);
getProducts()

function getProducts() {
  axios.get(api).then((res) => {
    if (!res.data.success) {
      console.log(res.data.message);
    }
    products.value = res.data.products.reverse();
    setTimeout(() => {
      loadScroll();
    }, 0);
  });
}
let target = ref(null)
function loadScroll() {
  const elemts = document.querySelectorAll(".fade-out");
  const targetPos = target.offsetTop;
  const { innerHeight } = window;
  elemts.forEach((item) => {
    if (innerHeight - item.offsetTop >= innerHeight - targetPos) {
      item.classList.add("fade-in");
    }
  });
}
function fadeInScroll() {
  const elemts = document.querySelectorAll(".fade-out");
  const targetPos = target.offsetTop;
  const { innerHeight } = window;
  const windowY = window.scrollY;
  elemts.forEach((item) => {
    if (windowY + targetPos - item.offsetTop >= innerHeight - targetPos) {
      item.classList.add("fade-in");
    } else {
      item.classList.remove("fade-in");
    }
  });
}

onMounted(() => {
  window.addEventListener("scroll", fadeInScroll);
});
onUnmounted(() => {
  window.removeEventListener("scroll", fadeInScroll);
});
</script>
<template>
  <v-card class="ml-2 mr-2 pa-2">
    <div class="p-5 position-relative">
      <h1 class="fs-4 text-secondary text-center mb-4">Lazy Loading</h1>
      <div
        class="position-fixed bottom-0 start-0 w-100 mb-5"
        ref="target"
      ></div>
      <div class="row g-3">
        <div class="col-4 p-2 fade-out" v-for="item in products" :key="item.id">
          <div
            class="shadow-sm rounded"
            style="min-height: 15rem"
            :style="{
              background: `url(${item.imageUrl}) no-repeat center center`,
              'background-size': 'cover',
            }"
          >
            <div class="p-2 text-white">{{ item.title }}</div>
          </div>
        </div>
      </div>
    </div>
  </v-card>
</template>

<style lang="sass" scoped>
.fade-out
	opacity: 0
	transform: translateY(10%)
	transition: all 1s

.fade-in
	opacity: 1
	transform: translateY(0)
	transition: all 1s
	transition-delay: .25s
</style>
